﻿using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using System;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Navigation;
using YZQ_DotNetArx.CAD;

namespace YZQ_DotNetArx.Test
{
    public static class 添加小室到模板
    {
        [CommandMethod("QYXS")]
        public static void QYXS()
        {
            PromptEntityOptions peo = new PromptEntityOptions("\n请选择小室");
            peo.AllowNone = true;
            peo.SetRejectMessage("\n您选择的不是多段线,请重新选择...");
            peo.AddAllowedClass(typeof(Polyline), false);
            PromptEntityResult per = Env.Editor.GetEntity(peo);
            if (per.Status != PromptStatus.OK)
                return;
            //用于存储小室的多段线
            Polyline pline = new Polyline();
            //创建一条多段线重绘用于检查
            Polyline newpline = new Polyline();
            //用于存储多段线的顶点
            List<Point3d> pts = new List<Point3d>();
            using (Transaction trans = Env.Database.TransactionManager.StartTransaction())
            {
                pline = trans.GetObject(per.ObjectId, OpenMode.ForWrite) as Polyline;
                //遍历多段线的所有段
                for (int i = 0; i < pline.NumberOfVertices; i++)
                {
                    //当前段的起点
                    Point3d startPoint = pline.GetPoint3dAt(i);
                    //当前段的终点
                    Point3d endPoint = new Point3d(0, 0, 0);
                    //如果i是最后一个点，那么它的终点为第一个点，否则为下一个点
                    if (i == pline.NumberOfVertices - 1)
                    {
                        endPoint = pline.GetPoint3dAt(0);
                    }
                    else
                    {
                        endPoint = pline.GetPoint3dAt(i + 1);
                    }
                    //如果当前段是圆弧，则取样圆弧上的点
                    if (pline.GetSegmentType(i) == SegmentType.Arc)
                    {
                        CircularArc3d arcSge = pline.GetArcSegmentAt(i);
                        Arc arc = new Arc();
                        arc.CreateArc(endPoint, arcSge.Center, arcSge.EndAngle);
                        arc.ReverseCurve();
                        //计算圆弧的长度
                        double arcLength = arc.GetDistanceAtParameter(arc.EndParam);
                        //采样间距
                        double sepDist = 0.2;
                        //采样段数
                        int sepNum = Convert.ToInt32(arcLength / sepDist);
                        for (int j = 0; j < sepNum; j++)
                        {
                            pts.Add(arc.GetPointAtDist(sepDist * j));
                        }
                    }
                    //如果是直线则直接在pts中添加它的起点
                    else if (pline.GetSegmentType(i) == SegmentType.Line)
                    {
                        pts.Add(startPoint);
                    }
                }
                newpline.CreatePolyline(pts.ToArray());
                newpline.ColorIndex = 1;
                newpline.Closed = true;
                Env.AddEntityToModelSpace(newpline);
                trans.Commit();
            }
            //提取小室的基准点
            PromptPointResult ppr = Env.Editor.GetPoint("\n请选择关联小室的点");
            if (ppr.Status != PromptStatus.OK)
                return;
            //小室的基准点
            Point3d basePoint = new Point3d(0, 0, 0);
            basePoint = ppr.Value;
            Env.Print(basePoint.ToString());
            //计算平移向量
            Vector3d vector = new Vector3d();
            vector = Point3d.Origin.GetVectorTo(basePoint);
            List<Point3d> mpts = new List<Point3d>();
            //将图形平移到原点
            foreach (Point3d p in pts)
            {
                mpts.Add(p - vector);
            }
            //提取小室的编码部分
            string roomName = "";
            PromptKeywordOptions keyWord = new PromptKeywordOptions("\n是否手动输入关联点号？[是(Y)/否(N)]<N>");  //设置关键字
            keyWord.Keywords.Add("Y");
            keyWord.Keywords.Add("N");
            keyWord.Keywords.Default = "N";
            keyWord.AppendKeywordsToMessage = false;
            PromptResult pKeyRes = Env.Editor.GetKeywords(keyWord);
            if (pKeyRes.StringResult == "Y")
            {
                PromptResult xsbmPr = Env.Editor.GetString("\n请输入小室点号");
                roomName = xsbmPr.StringResult;
            }
            else if (pKeyRes.StringResult == "N")
            {
                PromptEntityOptions bmpeo = new PromptEntityOptions("\n请选择小室关联点号");
                bmpeo.AllowNone = true;
                bmpeo.SetRejectMessage("\n选择的不是单行文字，请选择小室编码或输入");
                bmpeo.AddAllowedClass(typeof(DBText), false);
                PromptEntityResult bmper = Env.Editor.GetEntity(bmpeo);
                if (bmper.Status != PromptStatus.OK)
                    return;
                using (Transaction trans = Env.Database.TransactionManager.StartTransaction())
                {
                    DBText xsbmTxt = bmper.ObjectId.GetObject(OpenMode.ForWrite) as DBText;
                    if (xsbmTxt != null)
                    {
                        roomName = xsbmTxt.TextString;
                        xsbmTxt.ColorIndex = 1;
                    }
                    trans.Commit();
                    Env.Print(roomName);
                }
            }
            //连接roompnts字段
            string roompnts = "P";
            foreach (var item in mpts)
            {
                roompnts += item.X.ToString() + "," + item.Y.ToString() + "," + "0" + ",";
            }
            roompnts += mpts[0].X.ToString() + pts[0].Y.ToString() + "0";
            //标注距离提取及拼接asslines字段
            string asslines = "";
            int flag = 0; //标记循环次数
            TypedValue[] values = new TypedValue[1];
            values.SetValue(new TypedValue((int)DxfCode.Start, "Line"), 0);
            //将过滤条件复制给SelectionFilter对象
            SelectionFilter filter = new SelectionFilter(values);
            PromptSelectionOptions options = new PromptSelectionOptions();
            options.MessageForAdding = "\n请选择标注线";
            PromptSelectionResult result = Env.Editor.GetSelection(options, filter);
            if (result.Status != PromptStatus.OK)
                return;
            SelectionSet sSt = result.Value;
            if (sSt == null && sSt.Count == 0)
                return;
            using (Transaction trans = Env.Database.TransactionManager.StartTransaction())
            {
                foreach (var item in sSt.GetObjectIds())
                {
                    Line line = item.GetObject(OpenMode.ForRead) as Line;
                    asslines += (line.StartPoint - vector).X.ToString() + "," + (line.StartPoint - vector).Y.ToString() + "," + "0" + "," + (line.EndPoint - vector).X.ToString() + "," + (line.EndPoint - vector).Y.ToString() + "," + "0" + ",,@,";
                    flag++;
                    if (flag == sSt.GetObjectIds().Count())
                    {
                        asslines += (line.StartPoint - vector).X.ToString() + "," + (line.StartPoint - vector).Y.ToString() + "," + "0" + "," + (line.EndPoint - vector).X.ToString() + "," + (line.EndPoint - vector).Y.ToString() + "," + "0";
                    }
                }
                asslines = "L" + asslines;
            }
            //程序集当前路径
            string currentPath = Env.GetCurrentPath();
            //创建数据库链接
            DatabaseHelper sqlite = new DatabaseHelper("DataSource=" + currentPath + "\\jgdatabase.db");
            sqlite.WriteData("roomtemplate", new Dictionary<string, object> { { "name", roomName }, { "roompnts", roompnts }, { "asslines", asslines } });
            //sqlite.WriteData("roomtemplate", "name",roomName);
            //sqlite.WriteData("roomtemplate", "roompnts", roompnts);
            sqlite.Dispose();
        }
        //反转多段线
        [CommandMethod("FZ")]
        public static void FZ()
        {
            PromptEntityOptions peo = new PromptEntityOptions("\n请选择要反转的多段线");
            peo.AllowNone = true;
            peo.SetRejectMessage("\n您选择的不是多段线，请重新选择要反转的多段线");
            peo.AddAllowedClass(typeof(Polyline), false);
            PromptEntityResult per = Env.Editor.GetEntity(peo);
            if (per.Status != PromptStatus.OK)
                return;
            using (Transaction trans = Env.Database.TransactionManager.StartTransaction())
            {
                if (per.ObjectId.GetObject(OpenMode.ForWrite) is Polyline pline)
                {
                    pline.ReverseCurve();
                }
                else return;
                trans.Commit();
                Env.Print("多段线已反转");
            }

        }
        //选择直线
        [CommandMethod("XZX")]
        public static void XZX()
        {
            TypedValue[] values= new TypedValue[1];
            values.SetValue(new TypedValue((int)DxfCode.Start,"Line"),0);
            SelectionFilter filter = new SelectionFilter(values);
            PromptSelectionResult result=Env.Editor.GetSelection(filter);
            if (result.Status==PromptStatus.OK)
            {
                //清空当前选则集合
                Env.Editor.SetImpliedSelection(new ObjectId[0]);
                Env.Editor.SetImpliedSelection(result.Value.GetObjectIds());
            }
       
        }
    }
}
